package coreservlets.filters;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class ModificationFilter implements Filter {
	protected FilterConfig config;
	private HttpServletRequest request;
	private HttpServletResponse response;

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		this.request = (HttpServletRequest)req;
	    this.response = (HttpServletResponse)resp;
	    StringWrapper responseWrapper = new StringWrapper(response);
	    // Invoke resource, accumulating output in the wrapper.
	    chain.doFilter(request, responseWrapper);
	    // Turn entire output into one big String.
	    String modifiedResponse = doModification(responseWrapper.toString());
	    // Send modified response to the client
	    PrintWriter out = response.getWriter();
	    out.write(modifiedResponse);
	    System.out.println("after modify");
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
	}

	/**
	 * Saving off the request object for potential use by the child class.
	 */
	public HttpServletRequest getRequest() {
		return (request);
	}

	/**
	 * Saving off the response object for potential use by the child class.
	 */
	public HttpServletResponse getResponse() {
		return (response);
	}

	public abstract String doModification(String origResponse)
			throws IOException;
}
